package com.windy.i18n.interceptor;

import com.windy.i18n.config.I18nProperties;
import com.windy.i18n.constant.LocaleType;
import com.windy.i18n.constant.ResolverType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * Created by liyufeng on 2022/5/15
 */
@Slf4j
public class LocaleInterceptor implements AsyncHandlerInterceptor {
    private I18nProperties.Interceptor proper;

    public LocaleInterceptor() {

    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
        String newLocale = resolveLocal(request);
        if (newLocale != null) {
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if (localeResolver == null) {
                throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
            }

            try {
                localeResolver.setLocale(request, response, this.parseLocaleValue(newLocale));
            } catch (IllegalArgumentException var7) {
                log.debug("Ignoring invalid locale value [" + newLocale + "]: " + var7.getMessage());
            }
        }

        return true;
    }

    @Nullable
    protected Locale parseLocaleValue(String locale) {
        return LocaleType.getValue(locale);
    }

    @Nullable
    protected String resolveLocal(HttpServletRequest request) {
        String locale = null;
        if (ResolverType.HEADER.equals(proper.getType())) {
            locale = request.getHeader(proper.getName());
        } else if (ResolverType.BODY.equals(proper.getType())) {
            locale = request.getParameter(proper.getName());
        }
        return locale;
    }

    public void setProper(I18nProperties.Interceptor proper) {
        this.proper = proper;
    }
}
